package com.hmdp.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import static com.hmdp.entity.RedisConstants.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result queryShopById(Long id) {
        String shopInfo = redisTemplate.opsForValue().get(SHOP_INFO+id);
        //1.查询成功直接返回
        if (!StringUtils.isEmpty(shopInfo)) {
            return Result.ok(JSONUtil.toBean(shopInfo,Shop.class));
        }
        //2.数据库查询并判断
        Shop shop = getById(id);
        if (shop == null) {
            return Result.fail("店铺信息不存在！");
        }
        //3.存在则写入Redis
        redisTemplate.opsForValue().set(SHOP_INFO+id,JSONUtil.toJsonStr(shop));
        return Result.ok(shop);
    }
}
